package main

import (
	"bytes"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"mime/multipart"
	"net/http"
	"os"

	"github.com/astaxie/beego/httplib"
)

func uploadfile() {

	uploadFileToPaas("247e35ff320a4142a1050240cccccccc", "test3.wav", "/Users/Peter/Downloads/80906195949595-01053541117-13632366614.wav", "http://115.159.69.20:8081/ipcc/manager/file")
	return
	b := httplib.Post("https://ccc.qcloud.com/ipcc/manager/file")
	b.Param("appId", "247e35ff320a4142a1050240cccccccc")
	b.Param("filename", "test2.wav")
	b.PostFile("file", "/Users/Peter/Downloads/80906195949595-01053541117-13632366614.wav")
	str, err := b.String()
	if err != nil {
		fmt.Print(err)
	}

	fmt.Println(str)
}

func uploadFileToPaas(appid string, name, filePath string, url string) error {

	if len(url) < 10 {
		log.Fatal("Wrong url:", url)
		return errors.New("Invalid url")
	}

	file_data, err1 := ioutil.ReadFile(filePath)
	if err1 != nil {
		log.Fatal("readfile %s error %s", filePath, err1.Error())
		return err1
	}

	body := new(bytes.Buffer)
	w := multipart.NewWriter(body)
	//header
	content_type := w.FormDataContentType()

	//form
	w.WriteField("appId", appid)
	w.WriteField("filename", name)

	//file
	file, err := w.CreateFormFile("file", filePath)
	if err != nil {
		log.Fatal("create form file failed %s:", err.Error())
		return err
	}

	file.Write(file_data)
	w.Close()

	//request
	req, _ := http.NewRequest("POST", url, body)
	req.Header.Set("Content-Type", content_type)

	req.Header.Write(os.Stdout)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal("upload file %s  to %s error", filePath, err.Error())
		return err
	}

	defer resp.Body.Close()

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal("readAll err %s", err.Error())
		return err
	}

	log.Println("Ucpaas Upload file ", filePath, "result:",
		resp.StatusCode, "respone:", string(data))
	if string(data) != "0" && string(data) != "9" {
		return errors.New(string(data))
	}
	return nil
}
